/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisy.tools;

import cz.mzk.kramerius.rukopisyimport.sourceData.TeiDocument;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.DocumentException;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class TeiManager {

    private static final String TEI_FILE_SUFFIX = ".tei.xml";
    private final File rootDir;
    private final List<File> teiFiles = new ArrayList<File>();
    private Set<File> digitizedTeiFiles = null;

    public TeiManager(File rootDir) {
        this.rootDir = rootDir;
        loadTeiFiles();
    }

    private void loadTeiFiles() {
        File[] subdirs = findSubdirs();
        for (File subdir : subdirs) {
            addTeiFiles(subdir);
        }
    }

    private File[] findSubdirs() {
        return rootDir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isDirectory() && !file.getName().startsWith(".");
            }
        });
    }

    private void addTeiFiles(File subdir) {
        File[] files = subdir.listFiles(new FilenameFilter() {
            public boolean accept(File file, String name) {
                return name.endsWith(TEI_FILE_SUFFIX);
            }
        });
        teiFiles.addAll(Arrays.asList(files));
    }

    public Set<File> digitizedTeiFiles() {
        if (digitizedTeiFiles == null) {
            digitizedTeiFiles = loadDigitizedTeiFiles();
        }
        return digitizedTeiFiles;
    }

    private Set<File> loadDigitizedTeiFiles() {
        Set<File> result = new HashSet<File>();
        for (File file : teiFiles) {
            try {
                TeiDocument tei = new TeiDocument(file);
                if (tei.isDigitalized()) {
                    result.add(file);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(TeiManager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(TeiManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return result;
    }

    public boolean isDigitized(String signature) throws Exception {
        String filename = signature.concat(TEI_FILE_SUFFIX);
        for (File file : teiFiles) {
            if (file.getName().equals(filename)) {
                return digitizedTeiFiles().contains(file);
            }
        }
        throw new Exception("found no tei file '" + filename + "'");
    }
}
